<template>
  <div class="bigbox">
    <!-- 表头盒子 -->
    <div class="leftbox">
      <!-- 树节点过滤 -->
      <div>
        <el-input
          placeholder="输入关键字进行过滤"
          size="small"
          v-model="filterText"
        >
        </el-input>
      </div>
      <!-- 树组件 -->
      <div style="margin-top: 15px">
        <el-tree
          ref="tree"
          :props="props"
          :highlight-current="true"
          @node-click="handleNodeClick"
          :filter-node-method="filterNode"
          :load="loadNode"
          lazy
        >
          <span slot-scope="{ node, data }" class="slot-t-node">
            <template>
              <img
                class="node-img"
                v-if="data.bizOrgType == '03' || data.bizOrgType == '30'"
                src="../../assets/node0.png"
              />
              <img
                class="node-img"
                v-if="data.bizOrgType == '04' || data.bizOrgType == '40'"
                src="../../assets/node1.png"
              />
              <span :style="{ 'font-size': '14px' }">{{ node.label }}</span>
            </template>
          </span>
        </el-tree>
      </div>
    </div>
    <!-- 盒子主体 -->
    <div class="mainbox">
      <div class="top">
        <div class="timeSearch">
          <div class="change-type">月度</div>
          <el-date-picker
            size="small"
            v-model="time1"
            type="month"
            placeholder="选择开始月份"
          >
          </el-date-picker>
          <span style="margin: 0 20px; font-size: 14px; color: #606266"
            >至</span
          >
          <el-date-picker
            size="small"
            v-model="time2"
            type="month"
            placeholder="选择结束月份"
          >
          </el-date-picker>
        </div>
        <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
      </div>
      <div class="bodybox">
        <!-- 新增按钮 -->
        <!-- 循环图片盒子 -->
        <div class="table">
          <div class="titlebox">
            <div class="text">用电诊断数据</div>
            <TopTitle @command="command" @daochu="daochu" @shuaxin="shuaxin">
              <template #otherbutton>
                <el-button type="primary" size="small" @click="submit('add')">
                  <i style="margin-left: 0px" class="el-icon-plus"></i>新增
                </el-button>
              </template>
            </TopTitle>
          </div>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            border
            id="exportTabyong"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center'
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column
              align="center"
              type="index"
              width="50"
              label="序号"
            >
            </el-table-column>
            <el-table-column align="center" prop="month" label="月度">
            </el-table-column>
            <el-table-column align="left" prop="customerNo" label="户号">
            </el-table-column>
            <el-table-column align="left" prop="customerName" label="户名">
            </el-table-column>
            <el-table-column
              align="center"
              prop="marketizationAttributeName"
              label="市场户属性"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="declareWayName"
              label="计费方式"
            >
            </el-table-column>
            <el-table-column align="right" prop="ecValueMT" label="总电量">
            </el-table-column>
            <el-table-column align="right" prop="totalCharge" label="总电费">
            </el-table-column>
            <el-table-column
              align="center"
              prop="pft"
              label="功率因数"
              width="200"
            >
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 22px;
                      color: rgb(64, 149, 229);
                      margin-right: 20px;
                      cursor: pointer;
                    "
                    class="el-icon-edit"
                    @click="edit(scope.row)"
                  ></i
                ></el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top"
                >
                  <i
                    style="font-size: 22px; color: red; cursor: pointer"
                    class="el-icon-delete"
                    @click="del(scope.row.id)"
                  ></i
                ></el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            class="pagination"
            layout="prev, pager, next"
            :current-page.sync="pageobj._pageNo"
            @current-change="chaxun"
            :total="total"
          >
          </el-pagination>
        </div>
        <!-- 新增/修改弹框 -->
        <div>
          <el-dialog
            :show-close="true"
            :visible.sync="dialogVisible"
            width="500px"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            :before-close="diaClose"
            :center="true"
          >
            <div class="dialog">
              <!-- 企业下拉 -->
              <el-form
                ref="dialogForm"
                :rules="rules"
                :model="dialogForm"
                label-width="110px"
              >
                <el-form-item label="维护组织" prop="orgName">
                  <el-select
                    disabled
                    style="width: 100%"
                    v-model="dialogForm.orgName"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in options"
                      :key="index"
                      :label="item.orgName"
                      :value="item.orgNo"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="月份：" prop="month">
                  <el-date-picker
                    v-model="diaTime"
                    type="month"
                    placeholder="请选择月份"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-form>
              <!-- 弹窗内容 -->
            </div>
            <div style="margin-top: 10px; text-align: center">
              <button
                @click="addInner"
                style="
                  width: 300px;
                  height: 40px;
                  background-color: #3b8eea;
                  color: #fff;
                  border: none;
                  margin-top: 20px;
                "
              >
                获取系统数据
              </button>
            </div>
          </el-dialog>
          <el-dialog
            width="50%"
            :show-close="true"
            :visible.sync="innerVisible"
            append-to-body
            :close-on-click-modal="false"
            :destroy-on-close="true"
            :before-close="innerClose"
          >
            <EditDialogFrom
              :timeType="true"
              :formItem="formItem"
              ref="EditDialogFrom"
              @editSubmit="innerSubmit"
            />
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { gettreelist, gettreexiaji } from '../../api/userscreen'
import EditDialogFrom from './components/EditDialogFrom'
import dayjs from 'dayjs'
import { saveAs } from 'file-saver'
import {
  addReportApi,
  delReportApi,
  exportReportApi,
  getReportPageApi,
  saveReportApi
} from '@/api/monReport'
export default {
  name: 'monReportIndex',
  components: { EditDialogFrom },
  data() {
    return {
      orgNo: '',
      diaTime: '',
      timeType: true,
      tableData: [],
      formItem: {},
      loading: false,
      time1: new Date(new Date().getFullYear(), 0),
      time2: new Date(new Date().getFullYear(), 11, 31),
      entity: [],
      iissize: 'medium',
      options: [],
      filterText: '',
      dialogForm: {},
      smsselect: [],
      innerForm: [],
      rules: {},
      props: {
        label: 'bizOrgName',
        disabled: 'disabled'
      },
      dialogVisible: false,
      innerVisible: false,
      isedit: 'add',
      SCHSX: [],
      pageobj: {
        _pageNo: 0,
        _pageSize: 15
      },
      total: 0
    }
  },
  async created() {},
  async mounted() {},
  watch: {
    diaTime: {
      handler(newVal) {
        this.diaTime = dayjs(newVal).format('YYYY-MM')
      }
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    chushihua() {
      this.entity = []
      this.time1 = new Date(new Date().getFullYear(), 0)
      this.time2 = new Date(new Date().getFullYear(), 11, 31)
    },
    // 新增/修改
    submit(val) {
      this.isedit = val
      if (!this.dialogForm.orgName) {
        return this.$message.warning('请先选择企业')
      }
      this.dialogVisible = true
    },
    //  取消/弹框关闭
    quxiao() {
      this.dialogVisible = false
      if (this.isedit === 'add') {
        this.$refs.dialogForm.resetFields()
      } else {
        this.dialogForm = {
          orgName: this.orgName,
          orgNo: this.value
        }
      }
    },
    diaClose() {
      this.dialogVisible = false
      this.diaTime = ''
    },
    shuaxin() {
      this.chaxun()
      this.$message.success('列表刷新成功')
    },
    // 导出
    async daochu() {
      if (!this.orgNo) return this.$message('请选择企业')
      if (!this.time1 || !this.time2) return this.$message.error('请选择时间')
      const startTime = dayjs(this.time1).format('YYYY-MM')
      const endTime = dayjs(this.time2).format('YYYY-MM')
      const res = await exportReportApi({
        orgNo: this.orgNo,
        startMonth: startTime,
        endMonth: endTime,
        isParams: true
      })
      console.log(res)
      const blobContent = new Blob([res])
      const url = window.URL.createObjectURL(blobContent)
      saveAs(url, '用电诊断数据.xls')
    },
    // 查询分页信息
    async chaxun() {
      const startTime = dayjs(this.time1).format('YYYY-MM')
      const endTime = dayjs(this.time2).format('YYYY-MM')
      if (!this.time1 || !this.time2) return this.$message.error('请选择时间')
      if (this.orgNo) {
        try {
          this.loading = true
          const res = await getReportPageApi({
            _pageNo: this.pageobj._pageNo - 1,
            _pageSize: this.pageobj._pageSize,
            orgNo: this.orgNo,
            startMonth: startTime,
            endMonth: endTime
          })
          this.total = res.data.totalCount
          this.tableData = res.data.list
          console.log(res.data.list)
        } catch (e) {
        } finally {
          this.loading = false
        }
      } else {
        this.$message.error('请选择企业')
      }
    },
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    async addInner() {
      const res = await addReportApi({
        month: this.diaTime,
        orgName: this.orgName,
        orgNo: this.orgNo
      })
      console.log(res)
      if (res.code !== 200) {
        this.$message.error(res.message)
      } else {
        this.formItem = res.data.entity
        this.innerVisible = true
      }
    },
    // 树节点点击
    async handleNodeClick(val) {
      console.log(val)
      this.dialogForm.orgName = val.bizOrgName
      this.dialogForm.orgNo = val.bizOrgNo
      this.orgName = val.bizOrgName
      this.orgNo = val.bizOrgNo
      if (this.time1 && this.time2) {
        this.chaxun()
      }
    },
    // 树组件懒加载
    async loadNode(node, resolve) {
      const res = await gettreelist()
      if (!this.orgNo) {
        this.orgNo = res.data.list[0].bizManageNo
        this.chaxun()
      }
      if (node.level === 0) {
        // 初始的级数（最顶层）
        return resolve(res?.data.list) // 最顶层数据渲染为region
      }
      const ress = await gettreexiaji({ orgNo: node.data.bizOrgNo })
      if (node.level === 1) {
        return resolve(ress?.data.list)
      } else if (node.level === 2) {
        return resolve([])
      }
    },
    // 树节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.bizOrgName.indexOf(value) !== -1
    },
    // 编辑
    edit(item) {
      this.isedit = 'edit'
      console.log(item)
      this.formItem = { ...item }
      this.innerVisible = true
    },
    // 删除
    async del(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该诊断报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await delReportApi(id)
            if (res.code == 200) {
              this.$message.success('删除成功')
              this.chaxun()
            } else {
              this.$message.success(res.message)
            }
          } catch (e) {
            console.log(e)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async innerSubmit(item) {
      console.log(item)
      try {
        const res = await saveReportApi(item)
        if (res.code == 200) {
          this.$message.success('保存成功')
          this.dialogVisible = false
          this.innerVisible = false
        } else {
          this.$message.error(res.message)
        }
        console.log(res)
      } catch (e) {
      } finally {
        if (this.time1 && this.time2) this.chaxun()
      }
    },
    chongzhi() {
      this.time1 = ''
      this.time2 = ''
    },
    innerClose() {
      this.diaTime = ''
      this.formItem = {}
      this.dialogVisible = false
      this.innerVisible = false
    },

    toReport() {
      this.$router.push({
        name: 'mReportIndex',
        params: { param1: 'value1', param2: 'value2' }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.bigbox {
  background-color: #f1f1f1;
  min-height: 100%;
  padding: 10px;
  display: flex;
  .leftbox {
    min-width: 300px;
    background-color: #fff;
    padding: 20px;
  }
  .mainbox {
    flex: 1;
    margin-left: 10px;
    .top {
      padding: 0 40px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 80px !important;
      background-color: #fff;
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 10px;
      align-items: center;
      .timeSearch {
        display: flex;
        align-items: center;
        width: 500px;
      }
    }
    .bodybox {
      position: relative;
      background-color: #fff;
      padding: 20px;
      padding-bottom: 30px;
      min-height: 87.6vh;
      .pagination {
        position: absolute;
        right: 20px;
        bottom: 10px;
      }
      .table {
        .titlebox {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          .text {
            font-size: 16px;
          }
          .right {
            align-items: center;
            i {
              margin-left: 10px;
            }
            .bewdao {
              width: 63px;
              height: 32px;
            }
            .daochu {
              background-color: #1890ff;
              color: #fff;
              border: none;
              border-radius: 3px;
            }
          }
        }
      }
      .dialog {
        .title {
          font-size: 28px;
          margin-bottom: 30px;
        }
        .text {
          font-size: 12px;
          color: #3b8eea;
        }
      }
    }
  }
}

::v-deep .el-date-editor {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

::v-deep .el-range-separator {
  line-height: 25px;
}
.timeTitle {
  height: 50px;
}

.dropdown-list {
  text-align: center;
  width: 50px;
}

.change-type {
  width: 100px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 1);
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.node-img {
  width: 16px;
  height: 16px;
  margin-right: 5px;
  vertical-align: bottom;
}
</style>
